package cn.ray.springframework.core.io;

import cn.hutool.core.lang.Assert;
import org.springframework.util.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;

//处理classPath的流文件操作
public class ClassPathResource implements Resource {

    //资源路径
    private final String path;

    //加载资源的类加载器
    private ClassLoader classLoader;

    public ClassPathResource(String path){
        this(path,(ClassLoader)null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path,"path must be not null");
        this.path=path;
        this.classLoader=(classLoader!=null?classLoader: ClassUtils.getDefaultClassLoader());
    }

    @Override
    public InputStream getInputStream() throws IOException {
        //在指定位置找到path指定的资源文件并返回输入流
        InputStream is=classLoader.getResourceAsStream(path);
        if(is==null){
            throw new FileNotFoundException(
                    this.path + " cannot be opened because it does not exist");
        }
        return is;
    }
}
